/**
 * @FileName: CmccOrgDataImportService.java
 * @Author
 * @Description:
 * @Date 2016年3月18日 下午3:12:24
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service.ds;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.jfinal.kit.Prop;

import cn.hpclub.server.service.OrganizationService;
import cn.hpclub.server.service.ds.CmccFtpUtil.NoNewDataException;

public class CmccOrgDataImportService implements Job{
    private static final String LAST_IMPORT_FILE_TXT = "/lastImportFile.txt";

    /**
     * @param arg0
     * @throws JobExecutionException
     * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
     */
    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException{
        if(DsPropKit.getProp().getBoolean(DsPropKit.SWITCH_IMPORT_ORG_DATA)){
            downloadRemoteFileAndImportOrgData();
        } else{
            DsLog.log("未开启[导入机构数据]功能，放弃任务.");
        }
    }

    private void downloadRemoteFileAndImportOrgData(){
        CmccFtpUtil ftpUtils = getCmccFtpUtil();
        try{
            String tmpDirPath = getDirPath();
            DsLog.log("导入机构定时任务:开始从FTP下载和导入数据");
            File tmpFile = getOrgFilePath(tmpDirPath);
            String lastImportFileName = getLastImportFileName();
            String importFileName = ftpUtils.downloadFile(tmpFile.getAbsolutePath(), lastImportFileName);
            String result = OrganizationService.service.importData(new FileInputStream(tmpFile));
            saveImportFileName(importFileName);
            DsLog.log(result);
            DsLog.log("导入机构定时任务:流程结束");
        }
        catch(IOException e){
            e.printStackTrace();
            DsLog.log("导入机构定时任务:异常:" + e.getMessage());
        }
        catch(NoNewDataException e){
            DsLog.log("导入机构定时任务:" + e.getMessage());
        }
        finally{
            ftpUtils.closeConnection();
        }
    }

    private String getLastImportFileName(){
        String fileName = "";
        String dirPath = getDirPath();
        File file = new File(dirPath + LAST_IMPORT_FILE_TXT);
        if(!file.exists()){
            return "";
        }
        try{
            byte[] buff = new byte[1024];
            FileInputStream fis = new FileInputStream(file);
            int len = fis.read(buff);
            fileName = new String(buff, 0, len);
            fis.close();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        return fileName;
    }

    private void saveImportFileName(String fileName){
        String dirPath = getDirPath();
        File file = new File(dirPath + LAST_IMPORT_FILE_TXT);
        try{
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(fileName.getBytes("utf-8"));
            fos.close();
        }
        catch(IOException e){
            e.printStackTrace();
        }
    }

    private CmccFtpUtil getCmccFtpUtil(){
        Prop prop = DsPropKit.getProp();
        CmccFtpUtil ftpUtils = new CmccFtpUtil(prop.get("host"), prop.getInt("serverPort"), prop.get("userName"),
                prop.get("password"), prop.get("encoding"), prop.get("remotePath"));
        return ftpUtils;
    }

    private String getDirPath(){
        String tmpDirPath = Common.getRootDir() + "OrgData";
        Common.checkDir(tmpDirPath);
        return tmpDirPath;
    }

    private File getOrgFilePath(String tmpDirPath){
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-ddHHmmssSSS");
        String timestamp = sdf.format(new Date());
        String tmpFilePath = String.format("%s/%s%s.txt", tmpDirPath, "groupmsg_", timestamp);
        return new File(tmpFilePath);
    }
}
